package ml;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class HCRFFileFormat extends MLFileFormat {
	private BufferedWriter labelbw;

	public HCRFFileFormat(String trainingFile, DataModel dm) throws IOException {
		super(trainingFile + ".hcrf", dm);
		File labelFile = new File(trainingFile + ".labels");
		labelbw = new BufferedWriter(new FileWriter(labelFile));
	}

	@Override
	public void writeData() throws IOException {
		int nbrFeatures = dm.getNbrFeatures();
		int featuresToWrite = 0;
		for (FeatureVector fv : dm.getFeatureVectors()) {
			if (featuresToWrite == 0) {
				bw.append(nbrFeatures + "," + fv.getData().size() + "\n");
				labelbw.append(fv.getLabel() + "\n");
				featuresToWrite = nbrFeatures;
			}
			for (int i = 0; i < fv.size(); i++) {
				Data d = fv.getData().get(i);
				bw.append(d.getValue() + (i == fv.size() - 1 ? "\n" : ","));
			}
			featuresToWrite--;
		}
	}

	// // sparse format doesn't seem to work
	// @Override
	// public void writeData() throws IOException {
	// for (FeatureVector fv : dm.getFeatureVectors()) {
	// bw.append(fv.getNbrSequences() + " " + dm.getNbrFeatures() + " 0\n");
	// for (Data d : fv.getData()) {
	// bw.append((d.getRow()+1) + " " + (d.getColumn()+1) + " " + d.getValue() +
	// "\n");
	// }
	// lbw.append(fv.getLabel() + "\n");
	// }
	// }

	@Override
	public void writeFeatures() throws IOException {
	}

	@Override
	public void close() throws IOException {
		super.close();
		labelbw.flush();
		labelbw.close();
	}
}
